# -*- coding: utf-8 -*-
"""
__title__ = '模拟设备接入测试'
__author__ = 'Carlos'
__time__ = '2018/6/11'
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
"""


import time
import struct
import socket
import schedule
import _thread
import random
import datetime
# host = '127.0.0.1'  # 主机名
host = '52.83.144.116'  # 主机名
port = 17650    # 端口号
thread_num = 102  # 开启线程数
send_msg_tag = True  # 定时发数据开关
schedule_time = 10  # 在send_msg_tag==True 情况下设置发消息间隔时间

a = [0xaa, 0x21, 0x01, 0x18, 0x04,
     0x10, 0x01, 0x12, 0x5a, 0xcd,
     0xa7, 0xdf, 0x60, 0xa8, 0xb2,
     0x00, 0xfa, 0x82, 0xee, 0x83,
     0x80, 0x02, 0x92, 0x02, 0x62,
     0x93, 0x82, 0x06, 0xee, 0x10,
     0x28, 0x13, 0xdd]

lng = [114.018289,	112.790162999999,	112.959972,	112.666553,	108.793544,	107.488794,	116.752079,	105.630721,	109.850381,	109.765941,	114.290897,	109.674026,	103.283463,	112.685806,	110.988458,	101.002093,	104.762116999999,	111.168698999999,	112.798819,	107.342148999999,	110.254916999999,	106.007201999999,	103.289459,	102.674056999999,	111.588225,	111.159128,	101.687637999999,	111.151108,	116.277169,	101.2124,	108.027446,	111.318241,	104.170091,	114.280069,	116.653675999999,	102.387312999999,	114.871524999999,	104.196653,	114.239554,	110.065191,	115.833678999999,	105.689813,	103.845070999999,	109.548493,	109.50903,	111.000626,	104.886726,	116.085944,	107.336148,	107.672384999999,	105.448537,	116.263204,	104.867954,	112.534990999999,	112.648752,	102.796386,	105.218514,	105.662393999999,	114.718807,	112.344622,	101.903443,	116.759031,	113.555824,	108.937843,	114.493326,	111.057796,	101.998019,	116.95092,	112.160314,	106.219052999999,	116.904986999999,	103.275207999999,	111.490719,	111.209427999999,	112.351686,	115.702016,	107.690475999999,	111.855961999999,	116.939106999999,	109.072949999999,	104.273653,	109.545893999999,	101.80994,	101.693537999999,	114.903427999999, 120.1442400768,	120.1490404953,	120.0736020408,	120.2076857718,	120.1194349897,	119.9936717308,	118.3030060347,	118.2702434317,	117.0209753405,	117.0090370541,	116.9987488294,	116.9960773492,	117.6907197426,	117.6648557747,	117.6606698287,	118.2856195536,	115.16799930920658]
lat = [37.724686,	33.375673,	34.142721,	34.19238,	36.3980059999999,	34.026823,	38.821084,	35.40259,	33.003808,	35.587326,	32.85235,	38.256574,	38.649727,	35.639396,	34.02435,	33.592939,	38.197888,	38.458285,	36.471119,	35.885286,	33.251022,	31.393514,	32.52482,	32.881783,	39.3649459999999,	36.324552,	37.579878,	36.816266,	30.256345,	31.5830129999999,	36.2018629999999,	38.7396729999999,	37.146811,	37.690928,	34.9565599999999,	32.401148,	38.425988,	36.966245,	36.5903689999999,	33.0205149999999,	33.811959,	38.8468899999999,	34.413398,	31.27189,	33.697651,	30.768814,	31.604993,	30.234308,	32.821511,	34.1534849999999,	37.090492,	30.553735,	38.402355,	38.941345,	30.576586,	32.5099359999999,	36.8504189999999,	30.585755,	34.8698149999999,	36.555184,	35.447527,	37.20361,	34.729233,	30.557477,	39.1888359999999,	32.897953,	34.256215,	38.1728699999999,	36.0122609999999,	35.109761,	35.609714,	34.739509,	31.720785,	37.612023,	39.1825399999999,	30.309787,	30.201575,	33.042491,	36.532768,	36.735163,	39.3134389999999,	31.239825,	32.082111,	32.78036,	33.082772, 36.0040165207,	36.0053814051,	36.0027847232,	36.0328278553,	36.0639553049,	35.8933763931,	36.8044626602,	36.805792835,	36.6448362832,	36.6467017195,	36.6527919934,	36.6526714901,	36.1982318341,	36.203092111,	36.2117027862,	35.1241216764,	34.62990216029908]

# 生成指定id的当前时间的随机经纬度信息
def create_random_location(array_param, device_id, thread_id,lng,lat):


    array = array_param

    # 1，设置协议时间
    # 格式化输出
    regex = '%Y-%m-%d %H:%M:%S'
    # 获取当前时间
    dt = datetime.datetime.now()
    # 获取当前时间加8小时的时间戳
    timestamp = time.mktime(time.strptime((dt + datetime.timedelta(hours=8)).strftime(regex), regex))
    # 获取当前时间格式化字符串 '%Y-%m-%d %H:%M:%S'
    dt_rex = datetime.datetime.now().strftime(regex)
    # 截取字符串成协议需要的格式
    time_str = str(hex(int(str(timestamp)[0:str(timestamp).index('.')])))[2:]
    while len(time_str) < 8:
        time_str = '0'+time_str   # 不足8位的补0

    print(time_str)
    a[8] = int(time_str[0:2], 16)
    a[9] = int(time_str[2:4], 16)
    a[10] = int(time_str[4:6], 16)
    a[11] = int(time_str[6:8], 16)

    # 2,设置设备ID
    id_str = str(device_id)
    while len(id_str) < 10:
        id_str = '0'+id_str

    array[2] = int(id_str[0:2],16)
    array[3] = int(id_str[2:4],16)
    array[4] = int(id_str[4:6],16)
    array[5] = int(id_str[6:8],16)
    array[6] = int(id_str[8:10],16)

    # 随机生成温湿度 1
    temperature_min = 0
    temperature_max = 100
    temperature = random.uniform(temperature_min, temperature_max)
    if str(hex(int(temperature * 10))).find('-') == -1:
        temperature_str = str(hex(int(temperature * 10)))[2:]
    else:
        temperature_str = str(hex(int(temperature * (-10))))[3:]
    while len(temperature_str) < 4:
        temperature_str = '0' + temperature_str

    array[15] = int(temperature_str[0:2], 16)
    array[16] = int(temperature_str[2:4], 16)

    # 随机生成温湿度 3
    temperature2 = random.uniform(temperature_min, temperature_max)
    if str(hex(int(temperature2 * 10))).find('-') == -1:
        temperature_str2 = str(hex(int(temperature2 * 10)))[2:]
    else:
        temperature_str2 = str(hex(int(temperature2 * 10)))[3:]
    while len(temperature_str2) < 4:
        temperature_str2 = '0' + temperature_str2
    array[17] = int(temperature_str2[0:2], 16)
    array[18] = int(temperature_str2[2:4], 16)

    # 随机生成温湿度 4
    temperature3 = random.uniform(temperature_min, temperature_max)
    if str(hex(int(temperature3 * 10))).find('-') == -1:
        temperature_str3 = str(hex(int(temperature3 * 10)))[2:]
    else:
        temperature_str3 = str(hex(int(temperature3 * 10)))[3:]
    while len(temperature_str3) < 4:
        temperature_str3 = '0' + temperature_str3
    array[19] = int(temperature_str3[0:2], 16)
    array[20] = int(temperature_str3[2:4], 16)

    # 随机生成湿度
    humidity_min = 0
    humidity_max = 100
    humidity = random.uniform(humidity_min, humidity_max)
    humidity_str = str(hex(int(humidity * 10)))[2:]
    while len(humidity_str) < 4:
        humidity_str = '0' + humidity_str
    array[21] = int(humidity_str[0:2], 16)
    array[22] = int(humidity_str[2:4], 16)

    # 3,随机生成经纬度 start------------------------------------------

    # (1)-随机生成d纬度-----------------------------------

    lng_str = str(hex(int(lng*10**6)))[2:]

    # 组成新的8位16进制字符串，不足8位补齐8位
    while len(lng_str) < 8:
        lng_str = '0'+lng_str

    array[len(a) - 6] = int(lng_str[0:2], 16)
    array[len(a) - 5] = int(lng_str[2:4], 16)
    array[len(a) - 4] = int(lng_str[4:6], 16)
    array[len(a) - 3] = int(lng_str[6:8], 16)

    # (2)-随机生成经度--------------------------------------

    lat_str = str(hex(int(lat*10**6)))[2:]

    while len(lat_str) < 8:
        lat_str = '0'+lat_str

    array[len(a)-10] = int(lat_str[0:2],16)
    array[len(a)-9] = int(lat_str[2:4],16)
    array[len(a)-8] = int(lat_str[4:6],16)
    array[len(a)-7] = int(lat_str[6:8],16)

    # 打印日志
    print('thread-%s: %s send a msg : deviceID: %s ---{'
          'lng:%s,'
          'lat:%s,'
          'temperature:%s,'
          'temperature:%s,'
          'temperature:%s,'
          'humidity:%s}' % (thread_id, dt_rex, id_str, lng, lat, temperature, temperature2, temperature3, humidity))

    # # 随机生成经纬度 end------------------------------------------
    # # 组包返回
    #print(id_str, lng, lat)
    return struct.pack("%dB" % (len(array)), *array)


# 创建连接
def create_socket(thread_id):
    print('start to connect server ...')
    s = socket.socket()
    s.connect((host, port))
    device_id=9999999897
    if send_msg_tag:
        # 定时任务 s:socket a:包数据 thread_id:线程号 device_id:设备ID
        schedule.every(schedule_time).seconds.do(send_msg, s, a, thread_id, device_id+thread_id)
    else:
        # 只在连接时发送一条消息
        send_msg(s, a, thread_id, device_id)


# 发送socket消息
#  s:socket msg:包数据 thread_id:线程号 device_id:设备ID
def send_msg(s, msg, thread_id, device_id):
    data = create_random_location(msg, device_id, thread_id,lng[thread_id],lat[thread_id])
    s.send(data)


if __name__ == '__main__':
    # 创建多个线程
    try:
        for i in range(0, thread_num):
            _thread.start_new_thread(create_socket, (i, ))
    except():
        print("Error: unable to start thread")

while True:
        schedule.run_pending()
        time.sleep(1)